import { BaseAPI } from './baseAPI';
import type {
  RecommendationRequest,
  RecommendationResponse,
  RecommendationResult,
  TrendingContent,
  PersonalizedContent,
  RecommendationFeedback,
  RecommendationType,
} from '@/types';

/**
 * 推荐系统 API 服务类
 */
class RecommendationAPI extends BaseAPI {
  /**
   * 获取推荐内容
   */
  async getRecommendations(request: RecommendationRequest): Promise<RecommendationResponse> {
    const cacheKey = `recommendations_${JSON.stringify(request)}`;

    const response = await this.requestWithDeduplication(cacheKey, async () => {
      return await this.post<RecommendationResponse>('/api/recommendations', request);
    });
    return response.data;
  }

  /**
   * 获取个性化推荐
   */
  async getPersonalizedRecommendations(
    userId: string,
    limit = 20,
    excludeIds: string[] = []
  ): Promise<PersonalizedContent[]> {
    const response = await this.get<PersonalizedContent[]>(`/api/users/${userId}/recommendations`, {
      limit,
      exclude: excludeIds.join(','),
    });
    return response.data;
  }

  /**
   * 获取热门内容
   */
  async getTrendingContent(
    category?: string,
    timeRange: 'hour' | 'day' | 'week' | 'month' = 'day',
    limit = 20
  ): Promise<TrendingContent[]> {
    const response = await this.get<TrendingContent[]>('/api/recommendations/trending', {
      category,
      timeRange,
      limit,
    });
    return response.data;
  }

  /**
   * 获取相似内容
   */
  async getSimilarContent(contentId: string, limit = 10): Promise<RecommendationResult[]> {
    const response = await this.get<RecommendationResult[]>(`/api/recommendations/similar/${contentId}`, {
      limit,
    });
    return response.data;
  }

  /**
   * 获取基于协同过滤的推荐
   */
  async getCollaborativeRecommendations(
    userId: string,
    limit = 20
  ): Promise<RecommendationResult[]> {
    const response = await this.get<RecommendationResult[]>(
      `/api/users/${userId}/recommendations/collaborative`,
      { limit }
    );
    return response.data;
  }

  /**
   * 获取基于内容的推荐
   */
  async getContentBasedRecommendations(
    userId: string,
    limit = 20
  ): Promise<RecommendationResult[]> {
    const response = await this.get<RecommendationResult[]>(
      `/api/users/${userId}/recommendations/content-based`,
      { limit }
    );
    return response.data;
  }

  /**
   * 获取混合推荐
   */
  async getHybridRecommendations(
    userId: string,
    weights: {
      collaborative: number;
      contentBased: number;
      trending: number;
      personal: number;
    } = {
      collaborative: 0.3,
      contentBased: 0.3,
      trending: 0.2,
      personal: 0.2,
    },
    limit = 20
  ): Promise<RecommendationResult[]> {
    const response = await this.post<RecommendationResult[]>(
      `/api/users/${userId}/recommendations/hybrid`,
      { weights, limit }
    );
    return response.data;
  }

  /**
   * 获取实时推荐
   */
  async getRealTimeRecommendations(
    userId: string,
    currentQuery?: string,
    currentContentId?: string,
    limit = 10
  ): Promise<RecommendationResult[]> {
    const response = await this.post<RecommendationResult[]>(
      `/api/users/${userId}/recommendations/realtime`,
      {
        currentQuery,
        currentContentId,
        limit,
        timestamp: Date.now(),
      }
    );
    return response.data;
  }

  /**
   * 提交推荐反馈
   */
  async submitFeedback(feedback: Omit<RecommendationFeedback, 'id' | 'timestamp'>): Promise<void> {
    await this.post('/api/recommendations/feedback', {
      ...feedback,
      timestamp: Date.now(),
    });
  }

  /**
   * 批量提交推荐反馈
   */
  async submitBatchFeedback(feedbacks: Array<Omit<RecommendationFeedback, 'id' | 'timestamp'>>): Promise<void> {
    await this.post('/api/recommendations/feedback/batch', {
      feedbacks: feedbacks.map(feedback => ({
        ...feedback,
        timestamp: Date.now(),
      })),
    });
  }

  /**
   * 获取推荐解释
   */
  async getRecommendationExplanation(recommendationId: string): Promise<{
    reasons: Array<{
      type: string;
      description: string;
      weight: number;
      evidence: string[];
    }>;
    confidence: number;
    algorithm: string;
  }> {
    const response = await this.get<{
      reasons: Array<{
        type: string;
        description: string;
        weight: number;
        evidence: string[];
      }>;
      confidence: number;
      algorithm: string;
    }>(`/api/recommendations/${recommendationId}/explanation`);
    return response.data;
  }

  /**
   * 更新用户偏好
   */
  async updateUserPreferences(
    userId: string,
    preferences: {
      categories: string[];
      contentTypes: string[];
      languages: string[];
      excludeCategories?: string[];
      excludeSources?: string[];
    }
  ): Promise<void> {
    await this.put(`/api/users/${userId}/preferences`, preferences);
  }

  /**
   * 获取推荐统计
   */
  async getRecommendationStats(
    userId: string,
    timeRange: 'day' | 'week' | 'month' = 'week'
  ): Promise<{
    totalRecommendations: number;
    clickedRecommendations: number;
    clickThroughRate: number;
    topCategories: Array<{
      category: string;
      count: number;
      ctr: number;
    }>;
    algorithmPerformance: Array<{
      algorithm: string;
      impressions: number;
      clicks: number;
      ctr: number;
    }>;
  }> {
    const response = await this.get<{
      totalRecommendations: number;
      clickedRecommendations: number;
      clickThroughRate: number;
      topCategories: Array<{
        category: string;
        count: number;
        ctr: number;
      }>;
      algorithmPerformance: Array<{
        algorithm: string;
        impressions: number;
        clicks: number;
        ctr: number;
      }>;
    }>(`/api/users/${userId}/recommendations/stats`, { timeRange });
    return response.data;
  }

  /**
   * 刷新推荐缓存
   */
  async refreshRecommendations(userId: string): Promise<void> {
    await this.post(`/api/users/${userId}/recommendations/refresh`);
  }

  /**
   * 获取推荐多样性分析
   */
  async getDiversityAnalysis(userId: string): Promise<{
    categoryDiversity: number;
    sourceDiversity: number;
    contentTypeDiversity: number;
    temporalDiversity: number;
    overallDiversity: number;
  }> {
    const response = await this.get<{
      categoryDiversity: number;
      sourceDiversity: number;
      contentTypeDiversity: number;
      temporalDiversity: number;
      overallDiversity: number;
    }>(`/api/users/${userId}/recommendations/diversity`);
    return response.data;
  }

  /**
   * 设置推荐算法权重
   */
  async setAlgorithmWeights(
    userId: string,
    weights: Record<RecommendationType, number>
  ): Promise<void> {
    await this.put(`/api/users/${userId}/algorithm-weights`, weights);
  }

  /**
   * 获取推荐算法权重
   */
  async getAlgorithmWeights(userId: string): Promise<Record<RecommendationType, number>> {
    const response = await this.get<Record<RecommendationType, number>>(
      `/api/users/${userId}/algorithm-weights`
    );
    return response.data;
  }
}

// 创建推荐 API 实例
export const recommendationAPI = new RecommendationAPI();

// 导出类型和实例
export { RecommendationAPI };
export default recommendationAPI;
